package com.eco.fishway.config;

import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.WriteApi;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import javax.annotation.PreDestroy;

/**
 * @Author : xulinyu
 * @Date: 2024/7/8 16:02
 * @Description:
 */
@Data
@Configuration
public class InfluxdbConfig {

    @Value("${influxdb.url:}")
    private String url;

    @Value("${influxdb.bucket:}")
    private String bucket;

    @Value("${influxdb.org:}")
    private String org;

    @Value("${influxdb.token:}")
    private String token;

    private InfluxDBClient influxDBClient;
    private WriteApi writeApi;

    @Bean(name = "influxDBClient")
    public InfluxDBClient influxDBClient(){
        if (influxDBClient == null) {
            influxDBClient = InfluxDBClientFactory.create(url,token.toCharArray(),org,bucket);
        }
        return influxDBClient;
    }


    @Bean(name = "writeApi")
    @DependsOn(value = "influxDBClient")
    public WriteApi writeApi(){
        if (writeApi == null) {
            writeApi = influxDBClient.makeWriteApi();
        }
        return writeApi;
    }

    @PreDestroy
    public void destroy(){
        if (writeApi != null) {
            writeApi.flush();
        }
        if (influxDBClient != null) {
            influxDBClient.close();
        }
    }
}
